package outman.weibo.ui;

import java.util.ArrayList;

import outman.weibo.AccountInfo;
import outman.weibo.R;
import outman.weibo.WeiboClient;
import outman.weibo.WeiboDialogListener;
import outman.weibo.model.User;
import android.R.anim;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieSyncManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

    private static final String TAG = "LoginActivity";

    private Button authButton;
    private Button loginButton;
    private Button exitButton;

    private Spinner accountSelector;

    private String username;
    private String[] usernames;

    private WeiboClient client = WeiboClient.getInstance();
    private SharedPreferences preferences;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.login);

	loginButton = (Button) findViewById(R.id.front_login);
	authButton = (Button) findViewById(R.id.front_auth);
	exitButton = (Button) findViewById(R.id.front_exit);

	accountSelector = (Spinner) findViewById(R.id.front_account_selector);

	loginButton.setOnClickListener(this);
	authButton.setOnClickListener(this);
	exitButton.setOnClickListener(this);

	usernames = getUsernames();
	ArrayAdapter selectorAdapter = new ArrayAdapter(this,
		android.R.layout.simple_spinner_item, usernames);
	selectorAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	accountSelector.setAdapter(selectorAdapter);

	accountSelector.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> parent, View view,
		    int position, long id) {
		username = usernames[position];
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> parent) {
	    }
	});
    }

    @Override
    protected void onResume() {
	super.onResume();

    }

    @Override
    public void onClick(View v) {

	switch (v.getId()) {

	case R.id.front_auth:
	    oAuth();
	    break;

	case R.id.front_login:
	    toMainTabs(username);
	    break;

	case R.id.front_exit:
	    finish();

	default:
	    break;
	}
    }

    /**
     * 通过WebView去进行授权登录
     */
    private void oAuth() {
	client.authorize(this, new AuthDialogListener());
    }

    /**
     * loginButton的响应事件，设置好access_token后
     * 
     * @param username
     */
    private void toMainTabs(String username) {
	if (null == username || "".equals(username))
	    return;

	getAccountInfo(username);

	if (client.isSessionValid()) {
	    startActivity(new Intent(this, MainTabsActivity.class));
	} else {
	    Toast.makeText(this, "access_token已过期，请重新授权", Toast.LENGTH_LONG)
		    .show();
	}
    }

    /**
     * 获得所有授权过的用户名
     */
    private String[] getUsernames() {

	preferences = getSharedPreferences(AccountInfo.ACCOUNTS, MODE_PRIVATE);

	ArrayList<String> users = new ArrayList<String>();

	int i = 0;
	while (preferences.contains(AccountInfo.NICK + i)) {
	    users.add(preferences.getString(AccountInfo.NICK + i, ""));
	    i++;
	}
	return users.toArray(new String[] {});

    }

    /**
     * 获得某个用户的详细信息
     * 
     * @param username
     */
    private void getAccountInfo(String username) {

	for (int i = 0; i < usernames.length; i++) {
	    if (preferences.getString(AccountInfo.NICK + i, "")
		    .equals(username)) {

		client.setAccessToken(preferences.getString(AccountInfo.TOKEN
			+ i, ""));
		client.setExpiresIn(preferences.getString(
			AccountInfo.EXPIRES_IN, ""));

		break;
	    }
	}
    }

    class AuthDialogListener implements WeiboDialogListener {
	@Override
	public void onComplete(Bundle values) {
	    String token = values.getString("access_token");
	    String expires_in = values.getString("expires_in");

	    // 将获得的access_token和其过期的时间保存起来
	    client.setAccessToken(token);
	    client.setExpiresIn(expires_in);
	    Log.i(TAG, "access_token: " + token + "\nexpires_in: " + expires_in);

	    // 获得登录用户的uid去获得用户的昵称并保存起来
	    String uid = values.getString("uid");
	    User user = new User(values.getString("uid"), token);

	    // 将用户信息保存到sharedPreferences中
	    Log.i(TAG, user.getName());
	    saveAccount(user.getName(), uid, token, expires_in);
	    startActivity(new Intent(LoginActivity.this, MainTabsActivity.class));
	}
    }

    /**
     * 保存帐号信息 采用这种保存方式的原因是一般需要保存的用户只会有1,2个，但又需要保存access_token这样的参数
     * 
     * @param name
     * @param id
     * @param token
     * 
     */
    /*
     * 键： USER_*** + 一个数字,如 USER_NAME0,USER_NAME1，USER_TOKEN3;
     * 数字确定：第一个保存的为0号,第二个为1号，以此类推。
     */
    private boolean saveAccount(String name, String id, String token,
	    String expires_in) {

	for (int i = 0;; i++) {
	    // 遍历所有帐号
	    if (preferences.contains(AccountInfo.NICK + i)) {
		// 若已存在帐号，则不保存，并退出循环
		if (preferences.getString(AccountInfo.NICK + i, "")
			.equals(name)) {
		    return false;
		} else {
		    // 什么都不干
		}
	    } else {

		// 将新帐号保存到accounts.xml文件中，并跳出循环
		Editor editor = preferences.edit();
		editor.putString(AccountInfo.NICK + i, name);
		editor.putString(AccountInfo.ID + i, id);
		editor.putString(AccountInfo.TOKEN + i, token);
		editor.putString(AccountInfo.EXPIRES_IN, expires_in);
		editor.commit();
		return true;
	    }
	}
    }
}